﻿CREATE PROCEDURE [ServiceEngine].[CreateResource]
	@Name nvarchar(400),
	@Description ntext = null,	
	@InstanceID uniqueidentifier = null,
	@IDL nvarchar(max) = null,
	@IDLType nchar(100) = null,
	@BindingID uniqueidentifier,
	@Moniker xml = null,
	@RequestEntity uniqueidentifier = NULL,
	@ResponseEntity uniqueidentifier = NULL,
	@URI nvarchar(max) = NULL,
	@PolicyID uniqueidentifier = NULL,
	@ShareableProxy bit,
	@ID uniqueidentifier OUTPUT
	
AS
BEGIN
	DECLARE @ErrorMessage NVARCHAR(4000);
	DECLARE @ErrorSeverity INT;
	DECLARE @ErrorState INT;
	SET NOCOUNT ON;

	IF @ID IS NULL 
		SET @ID = newid();

	BEGIN TRY
		BEGIN TRANSACTION

		INSERT INTO ServiceEngine.Resources (ResourceID, InstanceID, IDL, IDLType, BindingID, Moniker, RequestEntity, ResponseEntity, URI, PolicyID, ShareableProxy)
		VALUES (@ID, @InstanceID, @IDL, @IDLType, @BindingID, @Moniker, @RequestEntity, @ResponseEntity, @URI, @PolicyID, @ShareableProxy)

		BEGIN TRY
			INSERT INTO ServiceEngine.Names (EntityID, EntityTypeID, EntityName, EntityDescription)
			VALUES (@ID, 16, @Name, @Description)
		END TRY
		BEGIN CATCH

			SELECT 
				@ErrorMessage = 'Attempt to insert Resource with duplicate name failed',
				@ErrorSeverity = 11,
				@ErrorState = ERROR_STATE();

			RAISERROR (@ErrorMessage, 
					   @ErrorSeverity,
					   1);
		END CATCH

		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();

		IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;

		RAISERROR (@ErrorMessage, 
				   @ErrorSeverity,
				   1);
	END CATCH

END